/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OptionTradeFragmentPresenter.java
 *   @Date: 1/9/19 4:21 PM
 *   @Author: chenjun
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.app.trade.presenter;

import android.text.TextUtils;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.trade.ui.OpenOptionDialog;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.NumberUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.LoginApi;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.OptionApi;
import io.bhex.sdk.trade.bean.AssetRecordResponse;
import io.bhex.sdk.trade.bean.CreateOrderRequest;
import io.bhex.sdk.trade.bean.OpenOrderResponse;
import io.bhex.sdk.trade.bean.OptionAssetListResponse;
import io.bhex.sdk.trade.bean.OptionFeeResponse;
import io.bhex.sdk.trade.bean.OptionHoldOrderResponse;
import io.bhex.sdk.trade.bean.OrderBean;
import io.bhex.sdk.utils.UtilsApi;

public class OptionTradeFragmentPresenter extends BaseTradeFragmentPresenter<OptionTradeFragmentPresenter.OptionTradeFragmentUI> {
    private static final String LOGTAG = "OptionTradeFragmentPresenter";
    private List<OptionHoldOrderResponse.OptionHoldOrderBean> mHoldOptionOrders = new ArrayList<>();
    private OpenOptionDialog openOptionDialog;
    private String optionFee = AppData.Config.OPTION_FEE_DEFAULT;

    public interface OptionTradeFragmentUI extends BaseTradeFragmentPresenter.BaseTradeFragmentUI {
        void showOptionHoldOrders(List<OptionHoldOrderResponse.OptionHoldOrderBean> datas);
    }
    /**
     * 获取当前委托
     */
    public void getCurrentEntrustOrders() {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }
        OptionApi.RequestOptionOpenOrder(getUI().getSymbols(), "", new SimpleResponseListener<OpenOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OpenOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    currentOrders = response.getArray();
                    if (currentOrders != null) {
                        getUI().showOpenOrders(currentOrders);
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取当前持仓
     */
    public void getOptionHoldOrders() {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }
        OptionApi.RequestOptionHoldOrder(getUI().getSymbols(), "", new SimpleResponseListener<OptionHoldOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OptionHoldOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    mHoldOptionOrders = response.array;
                    if (mHoldOptionOrders != null) {
                        getUI().showOptionHoldOrders(mHoldOptionOrders);
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    @Override
    public void getHistoryEntrustOrders(final boolean isLoadMore) {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }
        if (isLoadMore) {
            if (historyOrders != null) {
                if (!historyOrders.isEmpty()) {
                    mPageId = historyOrders.get(historyOrders.size() - 1).getOrderId();
                }
            }
        }else{
            mPageId ="";
        }

        String pageId = "";

        if (isLoadMore && !TextUtils.isEmpty(mPageId)) {
            //加载更多
            pageId = mPageId;

        }

        OptionApi.RequestOptionHistoryOrders(getUI().getSymbols(), pageId, new SimpleResponseListener<OpenOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
                if (isLoadMore) {
                    getUI().loadMoreComplete();
                }
            }

            @Override
            public void onSuccess(OpenOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<OrderBean> data = response.getArray();
                    if (data != null) {

                        if (isLoadMore) {
                            if (data != null) {
                                historyOrders.addAll(data);
                            }

                        } else {
                            if (data != null) {
                                historyOrders.clear();
                                historyOrders = data;
                            }
                        }
                        getUI().showHistoryOrders(historyOrders);

                        if (data.size()< AppData.Config.PAGE_LIMIT) {
                            getUI().loadEnd();
                        }else{
                            getUI().loadMoreComplete();
                        }
                    }else{
                        getUI().loadMoreComplete();
                    }

                }else{
                    getUI().loadMoreFailed();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (isLoadMore) {
                    getUI().loadMoreFailed();
                }
            }
        });
    }


    /**
     * 获取资产列表
     * @param token
     */
    protected synchronized void getAssetList(final String token){
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        if(token.equalsIgnoreCase(getUI().getQuoteToken())) {
            OptionApi.SubOptionTokenBalanceChange(token, new SimpleResponseListener<OptionAssetListResponse.OptionAssetBean>() {

                @Override
                public void onSuccess(OptionAssetListResponse.OptionAssetBean response) {
                    super.onSuccess(response);
                    if (getUI() == null || !getUI().isAlive() || response == null)
                        return;
                    if (response != null) {
                        getUI().updateAssettByToken(token, response.available);
                    } else {
                        //因为API接口返回的资产列表，如果没有资产，则没有改币种资产信息，所以为空，代表没有查询到余额 默认按零资产处理
                        getUI().updateAssettByToken(token, "0");
                    }
                }

                @Override
                public void onError(Throwable error) {
                    super.onError(error);
                }
            });
        }
    }

    protected synchronized void subSymbolOrder() {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        OptionApi.SubOptionSymbolOrderChange(getUI().getSymbols(), new SimpleResponseListener<OpenOrderResponse>() {
            @Override
            public void onSuccess(OpenOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<OrderBean> srcList = response.getArray();
                    boolean isOrderChange = false;
                    if(srcList != null && srcList.size() > 0) {
                        for (int i = srcList.size() -1; i >= 0 ; i--) {
                            OrderBean srcBean = srcList.get(i);
                            boolean hasSrcBean = false;
                            for (int j = 0; j < currentOrders.size(); j++) {
                                if(srcBean.getOrderId().equalsIgnoreCase(currentOrders.get(j).getOrderId())){
                                    isOrderChange = true;
                                    currentOrders.remove(j);
                                    if(getUI().getSymbols().equals(srcBean.getSymbolId())&&srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED")&& !srcBean.getStatus().equalsIgnoreCase("FILLED"))
                                        currentOrders.add(j, srcBean);
                                    hasSrcBean = true;
                                    break;
                                }
                            }
                            if(getUI().getSymbols().equals(srcBean.getSymbolId())&&hasSrcBean == false && srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED")&& !srcBean.getStatus().equalsIgnoreCase("FILLED"))
                                currentOrders.add(0,srcBean);
                            isOrderChange= true;

                        }
                        if (currentOrders != null&&isOrderChange) {
                            getUI().showOpenOrders(currentOrders);
                        }
                    }


                }
            }
        });

    }

    private  void subOptionHoldOrder(final String symbols) {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        OptionApi.SubOptionHoldOrderChange(symbols, new SimpleResponseListener<OptionHoldOrderResponse>() {
            @Override
            public void onSuccess(OptionHoldOrderResponse response) {
                super.onSuccess(response);
                try {

                    if (CodeUtils.isSuccess(response, true)) {
                        /*List<OptionHoldOrderResponse.OptionHoldOrderBean> srcList = response.array;
                        boolean isOrderChange = false;
                        if (srcList != null && srcList.size() > 0) {
                            for (int i = srcList.size() - 1; i >= 0; i--) {
                                OptionHoldOrderResponse.OptionHoldOrderBean srcBean = srcList.get(i);
                                boolean hasSrcBean = false;
                                for (int j = 0; j < mHoldOptionOrders.size(); j++) {
                                    if (srcBean.balanceId.equalsIgnoreCase(mHoldOptionOrders.get(j).balanceId)) {
                                        isOrderChange = true;
                                        mHoldOptionOrders.remove(j);
                                        //if(getUI().getSymbols().equals(srcBean.getSymbolId())&&srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED")&& !srcBean.getStatus().equalsIgnoreCase("FILLED"))
                                        //mHoldOptionOrders.add(j, srcBean);
                                        hasSrcBean = true;
                                        break;
                                    }
                                }
                                //if(getUI().getSymbols().equals(srcBean.getSymbolId())&&hasSrcBean == false && srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED")&& !srcBean.getStatus().equalsIgnoreCase("FILLED"))
                                if (getUI().getSymbols().equals(srcBean.symbolId) && Double.valueOf(srcBean.position) != 0)
                                    mHoldOptionOrders.add(0, srcBean);
                                isOrderChange = true;

                            }
                            if (mHoldOptionOrders != null && isOrderChange) {
                                getUI().showPlanningOrders(mHoldOptionOrders);
                            }
                        }*/
                        List<OptionHoldOrderResponse.OptionHoldOrderBean> list =  new ArrayList<>();
                        for (int i = 0; i < response.array.size(); i++) {
                            OptionHoldOrderResponse.OptionHoldOrderBean orderBean = response.array.get(i);
                            if(orderBean != null && orderBean.symbolId.equalsIgnoreCase(getUI().getSymbols())){
                                list.add(orderBean);
                            }
                        }
                        mHoldOptionOrders = list;

                        getUI().showOptionHoldOrders(mHoldOptionOrders);

                    }
                }
                catch (Exception e){}
            }
        });

    }

    /**
     * 获取资产
     * @param tokenId
     */
    protected void getAsset(final String tokenId) {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }
        if(tokenId.equalsIgnoreCase(getUI().getQuoteToken())) {
            AssetApi.RequestOptionTokenIdAsset(tokenId, new SimpleResponseListener<OptionAssetListResponse>() {
                @Override
                public void onFinish() {
                    super.onFinish();
                }

                @Override
                public void onSuccess(OptionAssetListResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response, true)) {
                        List<OptionAssetListResponse.OptionAssetBean> data = response.array;
                        if (data != null) {
                            if (data.size() > 0) {
                                OptionAssetListResponse.OptionAssetBean assetBean = data.get(0);
                                if (assetBean != null) {
                                    getUI().updateAssettByToken(tokenId, assetBean.available);
                                }
                            }
                        }
                    }
                }

                @Override
                public void onError(Throwable error) {
                    super.onError(error);
                }
            });
        }

    }

    /**
     * 下单
     *
     * @param isBuyMode
     * @param isLimitedPrice
     * @param exchangeId
     * @param symbol
     * @param price
     * @param amount
     */
    public void createOrder(boolean isBuyMode, boolean isLimitedPrice, String exchangeId, String symbol, String price, String amount) {

        CreateOrderRequest requestData = new CreateOrderRequest();
        requestData.exchangeId = exchangeId;
        requestData.symbol = symbol;
        requestData.isBuyMode = isBuyMode;
        requestData.isLimitedPrice = isLimitedPrice;
        requestData.price = price;
        requestData.amount = amount;
        OptionApi.RequestOptionCreateOrder(requestData, new SimpleResponseListener<OrderBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(OrderBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    ToastUtils.showShort(getActivity(), getString(R.string.string_create_order_success));
                    getUI().createOrderSuccess();
                    refreshCurrentOrders();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(),getString(R.string.string_create_order_failed));
            }
        });
    }

    /**
     * 撤销全部订单
     */
    public void revokeAllOrders() {
        if (!UserInfo.isLogin()) {
            return;
        }
        OptionApi.RequestOptionCancelAllOrder(getUI().getSymbols(), new SimpleResponseListener<ResultResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    DebugLog.w("Order", "撤单：" + response.isSuccess());
                    ToastUtils.showShort(getActivity(),getString(R.string.string_submit_revoke_all_orders));
                    refreshCurrentOrders();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(),getString(R.string.string_revoke_failed));
            }
        });
    }

    public void cancelOrder(String orderId) {
        OptionApi.RequestOptionCancelOrder(orderId, new SimpleResponseListener<OrderBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(OrderBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
//                    DebugLog.w("Order", "撤单：" + response.isSuccess());
                    ToastUtils.showShort(getActivity(),getString(R.string.string_revoke_success));
                    refreshCurrentOrders();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(),getString(R.string.string_revoke_failed));
            }
        });
    }

    @Override
    public void resetAllData(CoinPairBean coinPairBeanParam) {
        super.resetAllData(coinPairBeanParam);
        if (mHoldOptionOrders != null) {
            mHoldOptionOrders.clear();
            getUI().showOptionHoldOrders(mHoldOptionOrders);
        }

        getOptionHoldOrders();
        subOptionHoldOrder(getUI().getSymbols());
        getOptionFee();
    }
    @Override
    public void refresh() {
        super.refresh();
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }else{
            getOptionHoldOrders();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        getOptionHoldOrders();
        subOptionHoldOrder(getUI().getSymbols());

        getOptionFee();
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        if (visible && getUI().isSelected()) {
            if (UserInfo.isLogin() && UserInfo.getUserInfo()!= null && UserInfo.getUserInfo().openOption == false && (openOptionDialog == null || openOptionDialog.isShowing() == false)) {
                openOptionDialog = new OpenOptionDialog(getActivity());
                openOptionDialog.setNegativeButton(getString(R.string.string_option_opened), new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (openOptionDialog.getOpenChecked() == true) {
                            UtilsApi.RequestOpenOption(new SimpleResponseListener<ResultResponse>(){
                                @Override
                                public void onSuccess(ResultResponse data) {
                                    super.onSuccess(data);
                                    LoginApi.GetUserInfo();
                                }
                            });
                            if (openOptionDialog.isShowing()) {
                                openOptionDialog.dismiss();
                            }
                        }
                        /*if (builder.isShowing()) {
                            builder.dismiss();
                        }*/
                    }
                });
                openOptionDialog.setPositiveButton(getActivity().getString(R.string.string_cancel), new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 取消的操作
                        if (openOptionDialog.isShowing()) {
                            openOptionDialog.dismiss();
                        }
                    }
                });
                openOptionDialog.show();
            }

        }else{
        }
    }

    private void getOptionFee() {
        if(UserInfo.isLogin()) {
            OptionApi.RequestOptionFee(getUI().getExchangeId(), getUI().getSymbols(), new SimpleResponseListener<OptionFeeResponse>(){
                @Override
                public void onSuccess(OptionFeeResponse response) {
                    if (CodeUtils.isSuccess(response, true)) {
                        List<OptionFeeResponse.OptionFeeBean> data = response.array;
                        if(data != null && data.size() > 0){
                            for (int i = 0; i < data.size(); i++) {
                                if(getUI().getSymbols().equalsIgnoreCase(data.get(i).symbolId)){
                                    String fee = data.get(i).takerFeeRate;
                                    if(NumberUtils.sub(data.get(i).makerFeeRate, data.get(i).takerFeeRate) > 0d)
                                        fee = data.get(i).makerFeeRate;
                                    optionFee = fee;
                                    break;
                                }
                            }
                        }
                    }
                }
            });
        }
    }

    public String OptionFee(){
        return optionFee;
    }
}
